<template>
	<view style="background-color: white;">
		<!-- 地图 -->
		<map :latitude="latitude" :longitude="longitude" scale="15" style="width: 100%; height:100vh;"
		  :markers="markers" @markertap="onMarkerTap" ></map>
		
		<!-- 商家信息 -->
		<view class="com" v-if="selectedMerchant">
			<view class="carView">
				<!-- 左边部分 -->
				<view class="carItem1">
					<view>{{ selectedMerchant.name }}</view>
					<uni-rate :size="16" :value= selectedMerchant.rete  :readonly="true" />
					<view>最高评分：{{ selectedMerchant.rete }}分</view>
					<view>营业时间：{{selectedMerchant.startTime}}--{{selectedMerchant.endTime}}</view>
					<view>位置：{{selectedMerchant.address}}</view>
					<view>距离当前位置：{{distance}}</view>
				</view>
				<!-- 右边部分 -->
				<navigator url="">
					<view class="carItem2">
						<view>
							<image src="../../../static/images/头像.jpg" mode=""></image>
						</view>
					</view>
				</navigator>
			</view>
			<!-- 联系门店 -->
			<view class="but">
				<button style="font-size: 16px;padding: 5px 30px; line-height: 20px;border-radius: 20px;"  @click="toggle">联系门店</button>	
				<uni-popup ref="popup" type="bottom" background-color="#fff" @change="change">
					<view style="padding: 20px; text-align: center;">
						<view style="font-size: 18px; margin-bottom: 15px;">商家联系电话</view>
						<view style="font-size: 24px; color: #FF4E4F; margin-bottom: 20px;">400-123-4567</view>
						<button 
						style="background-color: #FF4E4F; color: white; border-radius: 20px;"
						@click="uni.makePhoneCall({ phoneNumber: '4001234567' })"
						>
						立即拨打
						</button>
					</view>
				</uni-popup>
				<navigator style="background-color: #FF4E4F;color: white;" :url="`/pages/index/store/store?id=${selectedMerchant?.id}`" >立即预定</navigator>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad} from '@dcloudio/uni-app'
import baseUrl from '../../utils/urlConfig.js'
const merchantList = ref([])

// 进入页面监听
onLoad(() => {
	getMerchant()
})
// 获取商家信息
function getMerchant() { 
	uni.request({
    url: baseUrl+'/yyq/merchant/list',
    method: 'get',
    header: {
		Authorization: uni.getStorageSync('Token')
	},
      success: (res) => {
        if(res.data && res.data.code === 200) { // 检查后端返回的状态码
          // console.log('商家信息', res.data.rows);
		   merchantList.value=res.data.rows
		// 获取商家数据后立即获取位置并更新标记
		getLocation()
		   // console.log(merchantList.value)
        }
      }
	})
}

// 获取当前位置信息
const latitude=ref('')
const longitude=ref('')
function getLocation(){
	uni.getLocation({
		success(res) {
			latitude.value=res.latitude
			longitude.value=res.longitude
			// 获取当前位置
			console.log(res)
			// 获取当前位置后更新商家标记		
			updateMerchantMarkers(res.latitude, res.longitude)
		}
	})
}
const selectedMerchant = ref(null) // 添加选中的商家信息
const markers = ref([])

// 添加距离计算函数
function calculateDistanceInMeters(lat1, lon1, lat2, lon2) {
  const R = 6371000; // 地球半径(米)
  const dLat = degToRad(lat2 - lat1);
  const dLon = degToRad(lon2 - lon1);
  const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(degToRad(lat1)) * Math.cos(degToRad(lat2)) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return R * c;
}

function degToRad(deg) {
  return deg * (Math.PI / 180);
}
// 距离
const distance = ref(0)
// 新增函数：更新商家标记
function updateMerchantMarkers(userLat, userLng) {

  markers.value = merchantList.value.map(merchant => {
    distance.value = calculateDistanceInMeters(
      userLat, userLng, 
      merchant.latitude, merchant.longitude
    ).toFixed(2)
    return {
      id: merchant.id,
      latitude: merchant.latitude,
      longitude: merchant.longitude,
      iconPath: '/static/home/maps/location.png',
      title: merchant.name,
    //   callout: {
    //     content: `${merchant.name} (${distance.value}m)`,
    //     color: "#fff",
    //     bgColor: '#000',
    //     borderRadius: 10,
    //     padding: 10,
    //     display: "ALWAYS",
    //   },
      merchantData: merchant // 保存完整商家信息
    }
  })
    // 自动选择距离最近的商家
	if(markers.value.length > 0) {
    const closestMerchant = [...markers.value].sort((a, b) => 
      a.merchantData.distance - b.merchantData.distance
    )[0]
    selectedMerchant.value = closestMerchant.merchantData
  }
}
// 修改onMarkerTap函数
function onMarkerTap(e){
  const markerId = e.detail.markerId
  selectedMerchant.value = markers.value.find(m => m.id === markerId)?.merchantData
  if(selectedMerchant.value) {
    // 更新底部商家信息显示
	distance.value= calculateDistanceInMeters(
      latitude.value, longitude.value,
      selectedMerchant.value.latitude, selectedMerchant.value.longitude
    ).toFixed(2)
  }
}

// 联系商家
const popup = ref(null)
function toggle() {
  popup.value.open('bottom')
}

function change(e) {
  console.log('弹窗状态:', e.show)
}

// const markers = ref( [
// 	{
// 		id: 999,
// 		latitude: 34.826128,
// 		longitude: 113.558902,
// 		width: 25,
// 		height: 25,
// 		iconPath: '/static/home/maps/location.png',
// 		callout: {  // 自定义一直显示的数据，自己的定位信息
// 			content: "附近门店>",
// 			color: "#fff",
// 			bgColor: '#000',
// 			borderRadius: 10,
// 			padding: 10,
// 			display: "ALWAYS",
// 		}
// 	},
// 	{
// 		id: 1,
// 		latitude: 34.826622,
// 		longitude: 113.556722,
// 		iconPath: '/static/home/maps/location.png',
// 		title: '店铺名A',
// 		rete: '商家评分',
// 		startTime:'开始营业时间',
// 		endTime:'结束营业时间',
// 		address: '详细地址'
// 	},
// 	{
// 		id: 2,
// 		latitude: 34.824521,
// 		longitude: 113.557732,
// 		iconPath: '/static/home/maps/location.png',
// 		title: '商家B',
// 		info: '地址B, 评分4.5' // 自定义信息
// 	},
// 	{
// 		id: 3,
// 		latitude: 34.827359,
// 		longitude: 113.557851,
// 		iconPath: '/static/home/maps/location.png',
// 		title: '商家C',
// 		info: '地址C, 评分4.5' // 自定义信息
// 	},
// 	{
// 		id: 4,
// 		latitude: 34.827537,
// 		longitude: 113.560137,
// 		iconPath: '/static/home/maps/location.png',
// 		title: '商家D',
// 		info: '地址D, 评分4.5' // 自定义信息
// 	}])

// const msk = ref({
// 	title:"商家",
// 	info:"位置"
// })
// 距离




//  商家信息
</script>

<style>
.carView {
		padding: 0 20px;
		margin-top: 35rpx;
		margin-bottom: 22rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.carItem1>view:nth-child(1) {
		font-size: 30rpx;
		font-weight: bold;
		margin-bottom: 15rpx;
	}

	.carItem1>view:nth-child(3) {
		font-size: 22rpx;
		font-weight: bold;
	}

	.carItem1>view:nth-child(4) {
		font-size: 22rpx;
		font-weight: bold;
	}

	.carItem1>view:nth-child(5) {
		font-size: 22rpx;
		font-weight: bold;
	}

	.carItem1>view:nth-child(6) {
		font-size: 22rpx;
		color: royalblue;
		font-weight: bold;
	}

	/* 右边部分 */
	image {
		width: 200rpx;
		height: 150rpx;
	}

	.carItem2 {
		margin-top: 30rpx;
	}

	/* 联系门店 */
	.btnView {
		margin-top: 30rpx;
		display: flex;
		justify-content: space-around;
		align-items: center;
	}

	.relaDoor {
		height: 300rpx;
		display: flex;
		flex-wrap: wrap;
		justify-items: center;
		align-items: center;
	}

	.doorItem {
		width: 700rpx;
		height: 80rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 28rpx;
		font-weight: bold;
	}
.com{
	position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: white;
		z-index: 999;
}
.but{
	display: flex;
	margin: 0 30px;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 10px;
}
.but navigator{
	padding: 2px 40px;
	border-radius: 20px;
}

</style>
